package com.active.hackson.database.service.impl;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.List;

import com.active.hackson.database.bean.Column;
import com.active.hackson.database.bean.Database;
import com.active.hackson.database.bean.DatabaseAccess;
import com.active.hackson.database.bean.DatabaseType;
import com.active.hackson.database.bean.PrimaryKey;
import com.active.hackson.database.bean.Table;
import com.active.hackson.database.connection.ConnectionGeneratorFactory;
import com.active.hackson.database.connection.IConnectionGenerator;
import com.active.hackson.database.service.IDatabaseAccessService;
import com.active.hackson.database.util.Converter;

public class DatabaseAccessService implements IDatabaseAccessService {
    @Override
    public Database getDatabase( DatabaseAccess access ) throws Exception {
        Database database = new Database();
        IConnectionGenerator connectionGenerator = ConnectionGeneratorFactory.getConnectionGenerator( access.getDatabaseType() );
        Connection connection = connectionGenerator.getConnection( generateDatabaseUrl( access ), access.getUserName(), access.getUserPass() );
        DatabaseMetaData dmd = connection.getMetaData();
        List< Table > tables = Converter.convertTables( dmd.getTables( null, null, null, null ) );
        if ( tables != null && tables.size() > 0 ) {
            for ( Table table : tables ) {
                List< PrimaryKey > primaryKeys = Converter.convertPrimaryKeys( dmd.getPrimaryKeys( null, null, table.getName() ) );
                List< Column > columns = Converter.convertColumns( dmd.getColumns( null, null, table.getName(), null ) );
                if ( primaryKeys != null && primaryKeys.size() > 0 ) {
                    for ( Column column : columns ) {
                        for ( PrimaryKey primaryKey : primaryKeys ) {
                            if ( column.getName().equalsIgnoreCase( primaryKey.getColumnName() ) ) {
                                column.setPrimaryKey( true );
                            }
                        }
                    }
                }
                table.setColumns( columns );
            }
        }
        database.setName( access.getDatabase() );
        database.setType( access.getDatabaseType() );
        database.setTables( tables );
        connectionGenerator.close( connection );
        return database;
    }

    private String generateDatabaseUrl( DatabaseAccess access ) {
        StringBuffer url = new StringBuffer();
        if ( DatabaseType.mysql == access.getDatabaseType() ) {
            url.append( "jdbc:mysql://" + access.getHost() + ":" + access.getPort() + "/" + access.getDatabase() );
        }
        return url.toString();
    }
}